package com.kfm.spring.controller;

import cn.hutool.core.lang.tree.Tree;
import com.kfm.spring.domain.SysUser;
import com.kfm.spring.domain.TreeMenu;
import com.kfm.spring.service.IndexService;
import com.kfm.spring.service.SysUserService;
import com.kfm.spring.util.Contains;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;

@Slf4j
@RestController
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private IndexService indexService;

    @GetMapping({"/","/login"})
    public ModelAndView login(){
        log.info("访问登录页面");
        return new ModelAndView("login");
    }
    @PostMapping("/login")
    public ModelAndView doLogin(SysUser sysUser, HttpSession session){
        ModelAndView mv = new ModelAndView();
        SysUser login = sysUserService.login(sysUser);
        if (login!=null){
            //登录成功
            session.setAttribute(Contains.LOGIN_FLAG,login);
            mv.setViewName("redirect:index");
        }else {
            //登录失败
            mv.addObject("msg","用户名或者密码错误");
        }
        return mv;
    }
    @GetMapping("/index")
    public ModelAndView index(ModelAndView mv,HttpSession session){

        mv.setViewName("index");
        //根据用户显示菜单
        SysUser sysUser = (SysUser)session.getAttribute(Contains.LOGIN_FLAG);
//        Collection<TreeMenu> menuByUser1 = indexService.getMenuByUser(sysUser.getId());

        List<Tree<Integer>> menuByUser = indexService.getMenuByUser2(sysUser.getId());

        mv.addObject("menus",menuByUser);
        return mv;
    }

}
